﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.Publishing.Administration;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Publishing.Internal;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Administration;
using System.Web;

namespace QuickDeployEnhancements
{
    public class QuickDeployInitiate : Microsoft.SharePoint.WebControls.LayoutsPageBase
    {
        protected Repeater JobRepeater;
        protected Label errormessage;

        private DataTable jrdata;

        private void UpdateData()
        {
            ContentDeploymentJobCollection cdjc = Microsoft.SharePoint.Publishing.Administration.ContentDeploymentJob.GetAllQuickDeployJobs();

            bool registerRefresh = false;

            jrdata = new DataTable();
            DataColumn jrdName = jrdata.Columns.Add("Name", typeof(string));
            DataColumn jrdIsEnabled = jrdata.Columns.Add("IsEnabled", typeof(bool));
            DataColumn jrdLastRunTime = jrdata.Columns.Add("LastRunTime", typeof(DateTime));
            DataColumn jrdLastStatusMessage = jrdata.Columns.Add("LastRunStatusMessage", typeof(string));
            DataColumn jrdId = jrdata.Columns.Add("Id", typeof(Guid));
            DataColumn jrdNextRunTime = jrdata.Columns.Add("NextRunTime", typeof(DateTime));
            DataColumn jrdQuickDeployItems = jrdata.Columns.Add("QuickDeployItems", typeof(int));
            DataColumn jrdLastStatus = jrdata.Columns.Add("LastStatus", typeof(string));

            foreach (ContentDeploymentJob job in cdjc)
            {
                string scurl = SPUrlUtility.CombineUrl(job.Path.SourceServerUri.ToString(), job.Path.SourceSiteCollection);
                using (SPSite site = new SPSite(scurl))
                {
                    if (site.ID.Equals(SPContext.Current.Site.ID))
                    {
                        DataRow jrdrow = jrdata.NewRow();
                        jrdrow[jrdName] = job.Name;
                        jrdrow[jrdIsEnabled] = job.IsEnabled;
                        jrdrow[jrdLastRunTime] = job.LastRunTime;
                        jrdrow[jrdLastStatusMessage] = job.LastStatusMessage;
                        jrdrow[jrdId] = job.Id;
                        jrdrow[jrdLastStatus] = job.LastStatus.ToString();
                        jrdrow[jrdNextRunTime] = job.NextRunTime;

                        string jobid = job.Id.ToString().ToLower();
                        SPQuery query = new SPQuery();
                        query.RowLimit = 999;
                        query.Query = "<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + jobid + "</Value></Eq></Where>";
                        SPList qdlist = site.RootWeb.Lists["Quick Deploy Items"];
                        jrdrow[jrdQuickDeployItems] = qdlist.GetItems(query).Count;
                        jrdata.Rows.Add(jrdrow);
                    }
                }

            }
            JobRepeater.DataSource = jrdata;
            JobRepeater.DataBind();
        }

        protected override void CreateChildControls()
        {
            errormessage.Text = null;

            UpdateData();
        
            base.CreateChildControls();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Start_Click(object sender, EventArgs e)
        {
            EnsureChildControls();

            Button btn = sender as Button;
            if (btn != null)
            {
                RepeaterItem repitm = btn.Parent as RepeaterItem;
                if (repitm != null)
                {
                    try
                    {
                        #region Get a reference to the specific QuickDeploy Job
                        DataRow jrrow = jrdata.Rows[repitm.ItemIndex];
                        Guid jobguid = (Guid)jrrow["Id"];

                        #endregion

                        #region Run the QuickDeploy Job
                        // Fiddle with the FormDigestSettings to prevent "The security validation for this page is invalid." exception

                        object o = HttpContext.Current.Items["HttpHandlerSPRequestContext"];
                        

                        try
                        {
                            HttpContext.Current.Items["HttpHandlerSPRequestContext"] = null;

                            HttpContext.Current.Items["FormDigestValidated"] = true;
                            SPContext.Current.Site.WebApplication.FormDigestSettings.Enabled = false;


                            ContentDeploymentJob job = Microsoft.SharePoint.Publishing.Administration.ContentDeploymentJob.GetInstance(jobguid);

                            job.Run(true);
                        }
                        finally
                        {
                            HttpContext.Current.Items["HttpHandlerSPRequestContext"] = o;
                        }
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        errormessage.Text = "An error occured:" + ex.Message;
                    }

                    UpdateData();
                }
            }
        }

        protected void Clear_Click(object sender, EventArgs e)
        {
            EnsureChildControls();

            Button btn = sender as Button;
            if (btn != null)
            {
                RepeaterItem repitm = btn.Parent as RepeaterItem;
                if (repitm != null)
                {
                    try
                    {
                        #region Get a reference to the specific QuickDeploy Job
                        DataRow jrrow = jrdata.Rows[repitm.ItemIndex];
                        Guid jobguid = (Guid)jrrow["Id"];

                        ContentDeploymentJob job = Microsoft.SharePoint.Publishing.Administration.ContentDeploymentJob.GetInstance(jobguid);
                        #endregion

                        #region Delete all QuickDeployObjects from the QuickDeploy List for this Job
                        string scurl = SPUrlUtility.CombineUrl(job.Path.SourceServerUri.ToString(), job.Path.SourceSiteCollection);
                        using (SPSite site = new SPSite(scurl))
                        {
                            SPList qdlist = site.RootWeb.Lists["Quick Deploy Items"];

                            StringBuilder sbDelete = new StringBuilder();
                            sbDelete.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");
                            string command = "<Method><SetList Scope=\"Request\">" + qdlist.ID +
                            "</SetList><SetVar Name=\"ID\">{0}</SetVar><SetVar Name=\"Cmd\">Delete</SetVar></Method>";

                            foreach (SPListItem item in qdlist.Items)
                            {
                                string titleguid = item.Title.ToLower();
                                if (titleguid.Equals(job.Id.ToString().ToLower(), StringComparison.InvariantCultureIgnoreCase))
                                {
                                    sbDelete.Append(string.Format(command, item.ID.ToString()));
                                }
                            }

                            sbDelete.Append("</Batch>");

                            site.RootWeb.ProcessBatchData(sbDelete.ToString());
                        }
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        errormessage.Text = "An error occured:" + ex.Message;
                    }
                    UpdateData();
                }
            }
        }


    }
}
